# coding: utf-8


from Katana import QtCore, QtGui, UI4, QT4Widgets, QT4FormWidgets
from Katana import NodegraphAPI, Utils
from Katana import UniqueName, FormMaster
import os.path
import ScriptActions as SA
import logging
log = logging.getLogger('dsMtlX_ResolveEditor')

Ver_Info = {
    1.0: u'2017.10.12，发布',
    1.1: u'2017.10.13，修正"CEL"表达式写入错误',
    1.2: u'2017.10.16, 忽略"color_space"设置，均为默认值"auto"',
    1.3: u'2017.10.20, 保留"normal_map"节点的"color_to_signed", "tangent_space"打开状态',
    1.4: u'2017.10.24, 修复"color3"类型参数不能正常赋值的错误',
    1.5: u'2017.10.25, 添加导入多重材质功能',
    1.6: u'2017.11.01, 添加导入aiMixShader功能；兼容 maya namespace',
    1.7: u'2017.11.03, 修正"alphaOffset"参数传递的错误',
    1.8: u'2017.12.11, maya导出时，过滤掉filter,filteroffset参数',
    1.9: u'2017.12.12, maya导出时，兼容aiStandardHair材质',
    2.0: u'2017.12.18, 修复复杂置换材质不能正确导入的错误，兼容BlendColor节点',
    2.1: u'2018.01.09, 修正"specularIOR"参数传递的错误；',
    2.2: u'2018.01.18, 修正"thinFilmIOR"参数传递的错误；如果image的color_space为默认值，'
         u'则强制修改为“linear”',
    2.3: u'2018.01.31, 修复 mtoa 中 ramp 与 ktoa 中 ramp_rgb 默认值不同的问题，'
         u'例如：mtoa中ramp的type默认为“v”，ktoa中默认为“custom”，'
         u'修复 mtoa 中 blendColors 与 ktoa 中 mix_rgba 默认值不同的问题，'
         u'例如：mtoa中color1,color2的type默认为“红蓝”，ktoa中默认为“黑”',
    #File: mvMaterialXWrite.py
    2.4: u'2018.02.07, 删除动画场景中除最顶层的其他名称空间，以保证与lookfile中层级对应'
         u'修改dsMtlX_Resolve默认location为：/root/world/geo ',
    #File: maya2scenegraphXML.py
    2.5: u'2018.02.24, 恢复导出文件的名称空间, 否则在有多次引用时会相互覆盖，'
         u'并通过限制引用名规则来防止文件名过长',
    #File: maya2scenegraphXML.py, dsScenegraphXML_export.py
    2.6: u'2018.02.26, 无论是否为默认值，均强制修改 image的 color_sapce为 linear',
    2.7: u'2018.02.28, 删除_tex文件最顶层级，|*_normal_Group|*_normal_model_GRP，直接为“_geometry_GRP”；'
         u'mayay file 的 alphaGain 和 alphaOffset 分别与 katana中的multiply offset对应',
    #File: mvMaterialXWrite.py
    2.8: u'2018.03.01, 修正对 “IOR” 属性与“R”通道的误判，造成参数值不能正常传递',
    2.9: u'2018.03.02, 取消根据是否有置换材质而自动添加 ArnoldObjectSettings 节点，由渲染部门自行添加',
    3.0: u'2018.03.05, 添加在分析场景时，如果未找到asset，则通过断言抛出异常',
    3.1: u'2018.03.07, 修改sgxml导出cache时的文件夹结构及命名',
    3.2: u'2018.03.15, 修复mtoa和ktoa中 arnoldStandsurface 的 subsurface 参数类型不对应的错误',
    3.3: u'2018.04.20, 修复mtoa aiColorToFloat 和ktoa中 rgb_to_float 节点类型不对应的错误'
}


class dsMtlX_ResolveEditor(QtGui.QWidget):

    def __init__(self, parent, node):
        """
        Initializes an instance of the class.
        """
        QtGui.QWidget.__init__(self, parent)
        self.__node = node
        nodeName = node.getName()
        Utils.UndoStack.OpenGroup('Upgrade "%s"' % nodeName)
        try:
            node.upgrade()
        except Exception as exception:
            log.exception('Error upgrading node "%s": %s' % (nodeName, str(exception)))
        finally:
            Utils.UndoStack.CloseGroup()

        locationParameter = self.__node.getParameter('location')
        locationParameter.setHintString("{'widget': 'newScenegraphLocation'}")
        matLocationParameter = self.__node.getParameter('matLocation')
        matLocationParameter.setValue(self.__node.getName(), 0)
        matLocationParameter.setHintString("{'help':'This namespace will be added on all the nodes resolved to avoid "
                                           "clashing from other dsMaterialX_Resolve nodes. It will also be set on the "
                                           "resulting NetworkMaterial namespace attribute. Remember to CTRL + MMB to "
                                           "dive inside this node for the resulting materials.'}")
        mtlXPathParameter = self.__node.getParameter('mtlXAsset')
        mtlXPathParameter.setHintString("{'widget': 'assetIdInput', 'help':'Select dsMaterialX XML file.', 'fileTypes': 'xml'}")
        mtlXModeParameter = self.__node.getParameter('mode')
        mtlXModeParameter.setValue('arnold', 0)
        mtlXModeParameter.setHintString("{'widget': 'popup', 'options': ['arnold']}")
        locationPolicy = UI4.FormMaster.CreateParameterPolicy(None, locationParameter)
        matLocationPolicy = UI4.FormMaster.CreateParameterPolicy(None, matLocationParameter)
        mtlXPathPolicy = UI4.FormMaster.CreateParameterPolicy(None, mtlXPathParameter)
        mtlXModePolicy = UI4.FormMaster.CreateParameterPolicy(None, mtlXModeParameter)
        widgetFactory = UI4.FormMaster.KatanaFactory.ParameterWidgetFactory
        locationWidget = widgetFactory.buildWidget(self, locationPolicy)
        matLocationWidget = widgetFactory.buildWidget(self, matLocationPolicy)
        mtlXWidget = widgetFactory.buildWidget(self, mtlXPathPolicy)
        mtlXModeWidget = widgetFactory.buildWidget(self, mtlXModePolicy)

        self._infoGroup = QtGui.QGroupBox(self)
        self._infoGroup.setLayout(QtGui.QVBoxLayout())
        self._infoGroup.setTitle('Version Information')
        self._info = QtGui.QPlainTextEdit(self._infoGroup)
        self._info.setReadOnly(True)
        self._info.setPlainText(GetPlainInfo(Ver_Info))
        self._infoGroup.layout().addWidget(self._info)


        self.__resolve = QtGui.QPushButton(self)
        self.__resolve.setText('Resolve')
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(locationWidget)
        mainLayout.addWidget(matLocationWidget)
        mainLayout.addWidget(mtlXWidget)
        mainLayout.addWidget(mtlXModeWidget)
        mainLayout.addWidget(self.__resolve)
        mainLayout.addWidget(self._infoGroup)
        self.setLayout(mainLayout)
        QtCore.QObject.connect(self.__resolve, QtCore.SIGNAL('clicked()'), self.onResolveClicked)

    def onResolveClicked(self):
        '''
        self.__node:                                        superTools.node
        self.__node.getParameter('mtlXAsset').getValue(0)   the path to XML file
        self.__node.getParameter('location').getValue(0)    the location of Assets
        self.__node.getParameter('matLocation').getValue(0) the location of XML file
        self.__node.getParameter('mode').getValue(0)        "3delight" or "arnold"
        @return:
        '''
        SA.RestoreToDefault(self.__node)
        if os.path.isfile(self.__node.getParameter('mtlXAsset').getValue(0)):
            SA.ResolveMtlXS(self.__node,
                            self.__node.getParameter('mtlXAsset').getValue(0),
                            self.__node.getParameter('location').getValue(0),
                            self.__node.getParameter('matLocation').getValue(0),
                            self.__node.getParameter('mode').getValue(0))
        else:
            log.warning('File do not exists.')

def GetPlainInfo(info):
    result = []

    keyList = info.keys()
    keyList = sorted(keyList)

    for key in keyList:
        result.append('Ver' + str(key) + ': ' + info[key])


    return '\n'.join(result)